﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AssetServiceHost.Controllers
{
    public class DemoController : BaseController
    {
        /// <summary>
        /// 创建一个资金账户
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <param name="balance">账户余额</param>
        /// <returns></returns>
        public async Task AddMoneyAccount(int userid,decimal balance)
        {
            //先判断账户是否存在
            if ( await this.CurrentDBContext.Connection.ExecuteScalarAsync<int>("select count(*) from MoneyAccount where UserId=@userid", new { userid }) == 0)
            {
                //标识支持分布式事务
                this.CurrentDBContext.BeginTransaction();


                await this.CurrentDBContext.Connection.ExecuteAsync("insert into MoneyAccount (UserId,Balance) values (@userid,@balance)",
                   new { userid, balance }, (IDbTransaction)this.CurrentDBContext.CurrentTransaction);
            }
        }

        /// <summary>
        /// 支付
        /// </summary>
        /// <param name="userid">用户id</param>
        /// <param name="amount">支付金额</param>
        /// <returns></returns>
        public async Task Pay(int userid,decimal amount)
        {
            //标识支持分布式事务
            this.CurrentDBContext.BeginTransaction();

            if( await this.CurrentDBContext.Connection.ExecuteAsync("update MoneyAccount set balance=balance-@amount where UserId=@userid and balance>=@amount", new {
                userid,
                amount
            } , (IDbTransaction)this.CurrentDBContext.CurrentTransaction) == 0)
            {
                throw new ServiceException("余额不足");
            }
        }
    }
}
